<?php

namespace Management\Controller;

use Think\Controller;

use Myself\FileSystem;

class RefundOrderController extends BaseController {



	protected $m = NULL;

	protected $m_class = NULL;

	protected $m_config = NULL;

    // protected $statusArr=array(

    //     ['color'=>'dark','status'=>"正常"],

    //     ['color'=>'red','status'=>"退款申请"],

    //     ['color'=>'blue','status'=>"审核中"],

    //     ['color'=>'green','status'=>"退款完成"],

    //     ['color'=>'dark','status'=>"拒绝退款"],

    // );
	protected $statusArr=array("未处理","已处理");
	

	public function _initialize(){

		parent::_initialize();

		$this->m = M('order_log');

		

	}

    public function index(){
		header('Content-Type:text/html;charset=utf-8');
		$where=[];
		//-----------------搜索-------------------
        $key = I('key','');//关键字
		if(!empty($key)){
			$where['order_id'] = array('eq',$key);
			$this->assign('order_id',$key);
		}
		if(I('log_status')!==''){
			$where['log_status'] = array('eq',I('log_status'));
			$this->assign('log_status',I('log_status'));
		}
		if(I('log_type')!==''){
			$where['log_type'] = array('eq',I('log_type'));
			$this->assign('log_type',I('log_type'));
		}
		if(!empty(I('start') && !empty(I('end')))){
			$start = I('start');
			$end = I('end');
			$where['addtime'] = array('between',[$start,$end]);
			$this->assign('start',$start);
			$this->assign('end',$end);
		}

		$pageno = I('p',1,'int');
		$pageCount = 10;
		$list = $this->m->where($where)->page($pageno.','.$pageCount)->order('log_status asc')->select();

		$this->assign('list',$list);// 赋值数据集

		$count = $this->m->where($where)->count();// 查询满足要求的总记录数

		$this->assign('count',$count);// 赋值分页输出	

		$Page = new \Think\Page($count,$pageCount);// 实例化分页类 传入总记录数和每页显示的记录数

		$show = $Page->showManage();// 分页显示输出

		$this->assign('page',$show);// 赋值分页输出
		$this->assign('statusArr',$this->statusArr);// 赋值分页输出

		$this->display('index');

    }
    //编辑日志
	public function edit(){
		if(empty(I('log_id'))){
			$arr['order_id'] = I('id',0,'int');
			$arr['order_no'] = I('order_no');
		}else{
			$arr = M('order_log')->where(['log_id'=>I('log_id')])->find();
		}
		$this->assign('arr',$arr);
		$this->display('edit');
    }
    //保存工单
    public function save(){
    	$data =I('post.');
    	// ll($data);die;
    	if(!empty($data['log_id'])){
    		$res = M('order_log')->where(['log_id'=>$data['log_id']])->save($data);
    	}else{
    		$data['addtime'] = date('Y-m-d H:i:s',time());
    		$res = M('order_log')->add($data);
    	}
    	 $this->selectPage_ajax(array('status'=>0,'act' => '操作成功', 'back_url' =>  U('RefundOrder/index'),'jump_url' => U('RefundOrder/index')));
    }
	public function edit1(){

		$id = I('id',0,'int');

		$dataInfo = $this->m->find($id);

		$dataInfo['order_detail']=M('order_detail')->find($dataInfo['order_detail_id']);

		$this->assign('dataInfo',$dataInfo);



		$this->assign('back_url',$_SERVER['HTTP_REFERER']);



        $this->assign('statusArr',$this->statusArr);// 状态

        $this->assign('storeList',M('store')->field('id,title_cn')->select());

		$this->display('edit');

    }

	public function save1(){

		

		$temp = $this->m->create();



		//$temp['overtime'] = strtotime($temp['overtime']);

		if($temp['id']){

            if($temp['status']==3){

                $refundInfo=$this->m->find($temp['id']);

                $orderInfo=M('order')->where(['order_no'=>$refundInfo['order_no']])->find();

                $orderDetail=M('order_detail')->find($refundInfo['order_detail_id']);

                $res=A('Miniprogram/Wx')->refund([

                    'refund_no'=>$refundInfo['refund_no'],

                    'order_no'=>$refundInfo['order_no'],

                    'total_fee'=>$orderInfo['total_price']*100,

                    'refund_fee'=>$orderDetail['price']*100,

                ]);

                if($res['return_code']!='SUCCESS')

                    $this->selectPage_ajax(array('status'=>0,'act' => '退款失败', 'back_url' => I('back_url'),'jump_url' => U('RefundOrder/edit','id='.$temp['id'].'&lang='.I('post.lang','cn'))));

                if($res['err_code'])

                    $this->selectPage_ajax(array('status'=>0,'act' => $res['err_code_des'], 'back_url' => I('back_url'),'jump_url' => U('RefundOrder/edit','id='.$temp['id'].'&lang='.I('post.lang','cn'))));

            }

			$this->m->save($temp);

			M('order_detail')->save(array(

			    'id'=>$temp['order_detail_id'],

                'status'=>$temp['status']

            ));

			$count=M('order_detail')->where(['id'=>$refundInfo['order_detail_id'],'status'=>['neq',3]])->count();

			if(!$count)

			    M('order')->where(['order_no'=>$refundInfo['order_no']])->save(['status'=>3]);

            $this->selectPage_ajax(array('status'=>1,'act' =>'操作成功', 'back_url' => I('back_url'),'jump_url' => U('RefundOrder/edit','id='.$temp['id'].'&lang='.I('post.lang','cn'))));

        }else{

            $this->error('参数错误');

		}

	}

	public function del(){

		$id = I('log_id');
		$res = $this->m->where(['log_id'=>$id])->delete();
		$this->success($GLOBALS['notice']['success'][1]);

    }

	public function batch(){          ////批量操作方法



		

		$ids = I('id');

		$val = I('get.val');

		$field = I('get.field');

		

		

		

		if($ids){

			if(is_array($ids)){$ids=implode(",",$ids);}

			

			if ($this->m->where('id in ('.$ids.')')->save(array($field=>$val))){

				$ids=explode(",",$ids);

			    $this->success($GLOBALS['notice']['success'][2]);

			}else{

				$this->error($GLOBALS['notice']['error'][2]);

			}

		}else{

			$this->error($GLOBALS['notice']['warming'][1]);

		}		

    }

	public function ajaxFindNext(){



		$selValue = I('selValue','0','int');

		$areaNextId = I('areaNextId','','int');

		$domId = I('domId');

		$classList = $selValue?$this->m_class->where('parent_id='.$selValue)->select():array();

		$content = "";

		if(!count($classList)){

			echo 0;exit;

		}else{

		

			$content .= '<span id="'.$domId.'_'.$areaNextId.'">'."\n\t";

			$content .= '<select class="form-control input-small" name="class_id[]" onchange="javascript:findNext(this.value , '.$areaNextId.' , \''.$domId.'\')">'."\n\t";

			$content .= '<option value="0">请选择</option>'."\n\t";

			foreach($classList as $item){

			$selectedMark = $selValue==$item['id']?'selected':'';

			$content .= '<option value="'.$item['id'].'" '.$selectedMark.'>'.$item['class_name'].'</option>'."\n\t";

			}

			$content .= '</select>'."\n\t";

			$content .= '</span>'."\n\t";

		

			echo $content;exit;

		

		}

	}

	public function ajaxListInput(){

		header('Content-Type:text/html;charset=utf-8');

		$info = I('post.');

		$data[$info["fieldName"]] = $info["Val"];

		$data["log_id"] = $info["id"];

		if ($this->m->save($data)){

			echo "success";

		}else{

			echo "error";

		}

		exit;

	}

	//退款编辑页面
	public function order_edit(){
		$id = I('get.id');
		$info = M('order')->field(['id','order_no','advance_price'])->where(['id'=>$id])->find();
		$this->assign('info',$info);
		$this->display();
	}
	public function refund_money(){
		// M()->startTrans();
		$data = I('post.');
		$refund =$data['refund_fee'];//退款金额
		$order = M('order')->field(['id','order_no','advance_price','from','orderId','userId'])->where(['id'=>$data['id']])->find();
		if($order['from']=='baidu'){
			//百度退款
			$baidu['orderId'] = $order['orderId'];
			$baidu['userId']  = $order['userId'];
			$baidu['tpOrderId'] = $order['order_no'];
			$baidu['isSkipAudit'] = 1;//是否跳过审核，不需要百度请求开发者退款审核请传 1，默认为0； 0：不跳过开发者业务方审核；1：跳过开发者业务方审核
			$baidu['refundType'] = 2;//退款类型：1：用户发起退款；2：业务方客服退款；3：业务方服务异常退款
			$baidu['refundReason'] = 2;//退款原因
			$baidu['applyRefundMoney'] =$refund*100;//退款金额(分)
			$baidu['bizRefundBatchId'] = date('YmdHis').time().$order['id'];//退款流水号
			$Baidu=A('Miniprogram/Baidu');
	        $res= $Baidu->refund($baidu);
	        if($res['errno']==0){
	        	$status = M('order')->where(['id'=>$data['id']])->save(['status'=>6,'refund_price'=>$refund,'refund_no'=>$baidu['bizRefundBatchId']]);
	        	$this->selectPage_ajax(array('status'=>1,'act' =>'操作成功', 'back_url' => U('Order/index'),'jump_url' => U('Order/index')));
	        }else{
	        	$this->selectPage_ajax(array('status'=>1,'act' =>$res['msg'], 'back_url' => U('Order/index'),'jump_url' => U('Order/index')));
	        }
		}else{
			//wx退款方法
			$data['total_fee'] = $order['advance_price']*100;//总价
			$data['refund_fee'] = $data['refund_fee']*100;//退款金额
			$data['refund_no'] = date('YmdHis').time().$data['id'];
	        // ll($data);die;
			$pay=A('Miniprogram/Wx');
	        $res= $pay->refund($data);
	        if($res['result_code']=='SUCCESS'){
	        	$status = M('order')->where(['id'=>$data['id']])->save(['status'=>6,'refund_price'=>$refund,'refund_no'=>$data['refund_no']]);
	        	$this->selectPage_ajax(array('status'=>1,'act' =>'操作成功', 'back_url' => U('Order/index'),'jump_url' => U('Order/index')));
	        }else{
	        	$this->selectPage_ajax(array('status'=>1,'act' =>$res['err_code_des'], 'back_url' => U('Order/index'),'jump_url' => U('Order/index')));
	        }
		}
        // ll($res);die;

	}
	

	

	

}